﻿using System;
using System.Runtime.InteropServices;
using System.IO;

using Microsoft.SharePoint;

namespace LookupListBlog
{
    public partial class SiteProvisioning
    {
        /// <summary>
        ///  Define your own feature activation action code here
        /// </summary>
        public void OnActivated(SPFeatureReceiverProperties properties)
        {
            CorrectLookupLists(properties);
        }

        private void CorrectLookupLists(SPFeatureReceiverProperties properties)
        {
            SPWeb web = null;
            SPSite site = null;

            try
            {

                if (properties.Feature.Parent is SPWeb)
                {
                    web = properties.Feature.Parent as SPWeb;
                    site = web.Site;
                }
                else
                {
                    site = properties.Feature.Parent as SPSite;
                    web = site.RootWeb;
                }

                web.AllowUnsafeUpdates = true;

                // Fix the simple list
                ReplaceGuid(web, "MainList", "SimpleList", "SimpleField", "684FCA54-BDFD-4913-9FC9-9B7F41E8480D");
            }
            finally
            {
                // NOTE: The cleanup code may need to be revisited.  Comments are welcomed.  
                // From my understanding you need to be  sure to dispose of your web and
                // site references.  However, I believe you are not supposed to do that for
                // the RootWeb.  If so, this code will need to be updated to reflect that.
                // Microsoft is working on a tool to help identify where you need to dispose
                // of your SharePoint objects:
                // http://blogs.msdn.com/sharepoint/archive/2008/11/12/announcing-spdisposecheck-tool-for-sharepoint-developers.aspx

                if (web != null)
                {
                    web.Dispose();
                }
                if (site != null)
                {
                    site.Dispose();
                }
            }

        }

        private void ReplaceGuid(SPWeb web, string mainListName, string lookupListName, string fieldName, string tempGuid)
        {

            SPList lookupList = web.Lists[lookupListName];
            SPList mainList = web.Lists[mainListName];

            mainList.Fields[fieldName].SchemaXml = mainList.Fields[fieldName].SchemaXml.Replace(tempGuid, lookupList.ID.ToString());

            mainList.Update();

        }


    }
}
